// 获取伙伴学习目标云函数
const cloud = require('wx-server-sdk');

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });

const db = cloud.database();
const usersCollection = db.collection('users');
const goalsCollection = db.collection('goals');
const studyRecordsCollection = db.collection('study_records');

async function getUserInfo(openid) {
  try {
    const rec = await usersCollection.doc(openid).get();
    const u = rec && rec.data ? rec.data : {};
    return {
      openId: openid,
      nickName: u.nickName || '学习伙伴',
      avatarUrl: u.avatarUrl || '/assets/icons/avatar-placeholder.png'
    };
  } catch (e) {
    // 兜底默认
    return {
      openId: openid,
      nickName: '学习伙伴',
      avatarUrl: '/assets/icons/avatar-placeholder.png'
    };
  }
}

function calcDaysLeft(deadline) {
  if (!deadline) return 0;
  const d = new Date(deadline);
  const today = new Date();
  const diff = d.getTime() - today.getTime();
  const days = Math.ceil(diff / (1000 * 3600 * 24));
  return days > 0 ? days : 0;
}

// 云函数入口
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;

  if (!openid) {
    return { code: 401, message: '用户未登录', data: null };
  }

  const { partnerId: partnerIdFromReq, studyRecordId } = event || {};

  if (!partnerIdFromReq && !studyRecordId) {
    return { code: 400, message: '需要提供 studyRecordId 或 partnerId', data: null };
  }

  try {
    let partnerId = partnerIdFromReq;
    let currentRecord = null;

    // 通过 studyRecordId 校验与反查
    if (studyRecordId) {
      const sr = await studyRecordsCollection.doc(studyRecordId).get();
      if (!sr || !sr.data) {
        return { code: 404, message: '学习记录不存在', data: null };
      }
      currentRecord = sr.data;

      // 权限：只能查询自己的学习记录
      if (currentRecord.userId !== openid) {
        return { code: 403, message: '无权访问此学习记录', data: null };
      }

      // 优先采用记录上的伙伴ID
      if (!partnerId && currentRecord.partnerId) {
        partnerId = currentRecord.partnerId;
      }

      // 兜底：通过 matchId 反查另一条记录
      if (!partnerId && currentRecord.matchId) {
        const other = await studyRecordsCollection
          .where({
            matchId: currentRecord.matchId,
            userId: db.command.neq(openid)
          })
          .limit(1)
          .get();
        if (other && other.data && other.data.length > 0) {
          partnerId = other.data[0].userId;
        }
      }
    }

    if (!partnerId) {
      return { code: 404, message: '未找到伙伴记录', data: null };
    }

    // 伙伴用户信息
    const partnerInfo = await getUserInfo(partnerId);

    // 伙伴活跃目标
    const partnerGoalRes = await goalsCollection
      .where({ openid: partnerId, status: 'active' })
      .orderBy('createTime', 'desc')
      .limit(1)
      .get();

    if (partnerGoalRes.data && partnerGoalRes.data.length > 0) {
      const goal = partnerGoalRes.data[0];
      const daysLeft = calcDaysLeft(goal.deadline);
      return {
        code: 0,
        message: '获取伙伴目标成功',
        data: {
          // 兼容前端已有结构（扁平）
          title: goal.title,
          deadline: goal.deadline,
          daysLeft,
          // 附带伙伴信息（可选使用）
          partnerInfo
        }
      };
    } else {
      // 无活跃目标也返回伙伴信息
      return {
        code: 0,
        message: '伙伴没有活跃目标',
        data: null
      };
    }
  } catch (error) {
    console.error('getPartnerGoal 出错:', error);
    return { code: 500, message: '服务器错误', error: error.message };
  }
};